﻿using System;
using System.Diagnostics;
using System.Threading;
using Hallenberg.Core;
using Hallenberg.SmartClient.Interfaces;

namespace Hallenberg.SmartClient.Events
{
    class EventManager : IEventManager
    {
        private IServiceLocator m_Services;

        public EventManager(IServiceLocator services)
        {
            Debug.Assert(services != null);
            if (services == null)
            {
                throw new ArgumentNullException("services");
            }

            m_Services = services;
        }

        public void Register<TArgument>(bool async, EventHandler<EventArgs<TArgument>> eventHandler)
        {
            m_Services.RegisterInstance<HandlesEvent<TArgument>>(Guid.NewGuid().ToString(), new HandlesEventInline<TArgument>(async, eventHandler));
        }

        public void Raise<T>(object sender, T value)
        {
            Debug.Assert(sender != null);
            if (sender == null)
            {
                throw new ArgumentNullException("sender");
            }

            Debug.Assert(value != null);
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            foreach (HandlesEvent<T> eventHandler in m_Services.ResolveAll<HandlesEvent<T>>())
            {
                if (eventHandler.Async)
                {
                    ThreadPool.QueueUserWorkItem((object state) =>
                    {
                        object[] parameters = (object[])state;

                        ((IEventHandler)parameters[0]).HandleEvent(
                            parameters[1],
                            (EventArgs)parameters[2]);

                    }, new object[] { eventHandler, sender, new EventArgs<T>(value) });
                }
                else
                {
                    eventHandler.OnEvent(sender, new EventArgs<T>(value));
                }
            }
        }
    }
}
